package com.qianguo.shop.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.ResultData;
import com.eva.androidlibrary.utils.DevUtil;
import com.eva.androidlibrary.widget.CircleImageView;
import com.qianguo.shop.R;
import com.qianguo.shop.base.BaseTitleActivity;
import com.qianguo.shop.constant.ShopKeys;
import com.qianguo.shop.entity.OrderDetails;
import com.eva.androidlibrary.api.entity.OrderInfo;
import com.qianguo.shop.widget.IconFontTextView;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * Created by eva on 15/10/19.
 */

@EActivity(R.layout.activity_order_details)
public class OrderDetailsActivity extends BaseTitleActivity {

    private static final String LOG_TAG = OrderDetailsActivity.class.getSimpleName();

    public static final int ORDER_DETAILS_REQUEST = 0x1001;
    public static final int WEIGHT_FINISH = 0x10001;

    /**
     * 订单详情类型：初始
     */
    public static final int TYPE_INIT = 1;
    /**
     * 订单详情类型：称重
     */
    public static final int TYPE_WEIGHING = 2;

    @ViewById(R.id.avatar)
    CircleImageView mImgAvatar;         // 头像
    @ViewById(R.id.username)
    TextView mTxvUsername;              // 名称
    @ViewById(R.id.addr_value)
    TextView mTxvAddr;                  // 配送地址
    @ViewById(R.id.time_handle_value)
    TextView mTxvTimeHandle;            // 配送时间
    @ViewById(R.id.time_order_value)
    TextView mTxvTimeOrder;             // 下单时间
    @ViewById(R.id.expect_price_value)
    TextView mTxvExpectPrice;          // 预计价格
    @ViewById(R.id.actual_price_value)
    TextView mTxvActualPrice;           // 实际价格
    @ViewById(R.id.remarks_value)
    TextView mTxvRemarks;               // 备注
    @ViewById(R.id.mail_price_value)
    TextView mTxvMailPrice;             // 配送费
    @ViewById(R.id.fruit_list)
    LinearLayout mLlyFruitList;         // 水果清单
    @ViewById(R.id.btn_check)
    Button mBtnCheck;                   // 底部确认按钮
    @ViewById(R.id.actual_price)
    View mActualPrice;                  // 实称价格栏
    @ViewById(R.id.btn_im)
    IconFontTextView mTxvIm;            // IM按钮

    @Extra(ShopKeys.EXTRA_KEY_ORDER)
    OrderInfo mOrder;

    private int mType = 0;

    public static void jumpToOrderDetail(Context context, OrderInfo order) {
        Intent intent = new Intent();
        intent.setClass(context, OrderDetailsActivity_.class);
        intent.putExtra(ShopKeys.EXTRA_KEY_ORDER, order);
        context.startActivity(intent);
    }

    @Override
    protected void initializeUI() {
        mType = getIntent().getIntExtra("type", TYPE_INIT);

        if (mType == TYPE_INIT) {
            mBtnCheck.setText("接单");
        } else if (mType == TYPE_WEIGHING) {
            mBtnCheck.setText("确认总价");
            mActualPrice.setVisibility(View.VISIBLE);
        } else {
            if (DevUtil.isDebug()) {
                throw new IllegalArgumentException("type " + mType + " is invalid");
            } else {
                DevUtil.w(LOG_TAG, "type " + mType + " is invalid");
            }
        }

        getOrderDetail(mOrder.getOrderSN());
    }

    @Background
    void getOrderDetail(String orderId) {
        mApp.getApi().getOrder(mApp.getUser().getToken(), orderId, new HttpRequestCallback<OrderInfo>() {
            @Override
            public void onSuccess(int code, String msg, OrderInfo data) {
                onLoadOrderDetails(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(OrderDetailsActivity.this, msg);

            }
        });

    }

    @Click(R.id.btn_check)
    public void onCheckButtonClick(View view) {
        if (mType == TYPE_INIT) {
            //TODO 处理接单逻辑
            mBtnCheck.setText("确认总价");
            mActualPrice.setVisibility(View.VISIBLE);
            mType = TYPE_WEIGHING;
        } else {
            weight(mTxvActualPrice.getText().toString());
        }
    }

    @Background
    void weight(String price) {
        mApp.getApi().weight(mApp.getUser().getToken(), mOrder.getOrderSN(), (int) (Float.valueOf(price) * 100 / 100), new HttpRequestCallback<ResultData>() {
            @Override
            public void onSuccess(int code, String msg, ResultData data) {
                setResult(WEIGHT_FINISH);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(OrderDetailsActivity.this, msg);
            }
        });

    }

    @Click(R.id.btn_im)
    public void onImBtnClick(View view) {
        IMMessageActivity.jumpToIMMessageActivity(this, 2, 2, mOrder.getUserName());
    }

    // 加载订单详情
    @UiThread
    void onLoadOrderDetails(OrderInfo orderInfo) {
        mOrder = orderInfo;
        mTxvUsername.setText(orderInfo.getUserName());
        mTxvAddr.setText(orderInfo.getReceiverAddress());
        mTxvTimeHandle.setText(orderInfo.getDeliveryTime());
//        mTxvTimeOrder.setText(orderInfo.getCreatedAt());
//        mTxvExpectPrice.setText(orderInfo.getExpectPrice());
//        mTxvRemarks.setText(orderInfo.getRemarks());
        mTxvMailPrice.setText(String.valueOf(orderInfo.getDeliveryPrice()));

//        onLoadFruitList(orderInfo.getFruitList());
    }

    // 加载水果清单
    private void onLoadFruitList(List<OrderDetails.Fruit> fruitList) {
        mLlyFruitList.removeAllViews();
        if (fruitList == null) {
            return;
        }
        final Context ctx = this.getApplicationContext();
        final int SIZE = fruitList.size();
        for (int i = 0; i < SIZE; i++) {
            final OrderDetails.Fruit fi = fruitList.get(i);
            View itemView = createFruitItemView(ctx, fi);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
            mLlyFruitList.addView(itemView, lp);
        }
    }

    // 创建水果清单列表的item视图
    private View createFruitItemView(Context context, OrderDetails.Fruit fi) {
        RelativeLayout itemView = new RelativeLayout(context);

        // 设置水果名称
        TextView txvName = new TextView(context);
        txvName.setText(fi.getName());
        txvName.setTextColor(Color.BLACK);
        RelativeLayout.LayoutParams nLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
        nLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        itemView.addView(txvName, nLp);

        // 设置水果价格
        TextView txvPrice = new TextView(context);
        txvPrice.setText(fi.getPrice());
        txvPrice.setTextColor(Color.BLACK);
        RelativeLayout.LayoutParams pLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
        pLp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        itemView.addView(txvPrice, pLp);

        return itemView;
    }

    /**
     * 跳转到指定类型的订单详情
     * @param context 上下文对象
     * @param type 订单详情类型
     *             TYPE_INIT 初始
     *             TYPE_WEIGHING 称重
     */
    public static void jumpToOrderDetails(Activity context, int type) {
        if ((type & (TYPE_INIT | TYPE_WEIGHING)) == 0) {
            throw new IllegalArgumentException("type的值必须是OrderDetailsActivity.TYPE_INIT或者" +
                    "OrderDetailsActivity.TYPE_WEIGHING");
        }
        Intent intent = new Intent(context, com.qianguo.shop.activity.OrderDetailsActivity_.class);
        intent.putExtra("type", type);
        context.startActivityForResult(intent, ORDER_DETAILS_REQUEST);
    }

    /**
     * 跳转到初始的订单详情
     * @param context 上下文对象
     */
    public static void jumpToInfoOrderDetails(Activity context) {
        jumpToOrderDetails(context, TYPE_INIT);
    }

    /**
     * 跳转到称重的订单详情
     * @param context 上下文对象
     */
    public static void jumpToWeighingOrderDetails(Activity context) {
        jumpToOrderDetails(context, TYPE_WEIGHING);
    }

    @Override
    protected String getToolbarTitle() {
        return "订单详情";
    }
}
